package br.com.paiva.container.util;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import net.sourceforge.sannotations.utils.Scanner;
import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

public class ConfigureSessionFactoryBean extends AnnotationSessionFactoryBean {

	private List<String> includePackages = new ArrayList<String>();

	public void setIncludePackages(List<String> includePackages) {
		this.includePackages = includePackages;
	}

	protected void postProcessAnnotationConfiguration(final AnnotationConfiguration config) throws HibernateException {
		final AnnotationConfiguration annConfig = config;
		final Scanner sc = new Scanner();

		for (final Class<?> c : sc.getClasses()) {

			if (!includePackages.isEmpty()) {

				for (String regex : includePackages) {

					System.out.println(c.getPackage().getName());

					if (c.getPackage().getName().startsWith(regex) && c.getAnnotation(Entity.class) != null) {
						annConfig.addAnnotatedClass(c);
					}
				}
			}
		}
	}
}